package com.cskaoyan.controller;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.lzpackage.lz_wx.*;
import com.cskaoyan.mapper.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.lang.System;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @USER: cuiweiguo#
 * @DATE: 2022/5/11
 * @TIME: 3:32
 * @PROJECT_NAME: mallproject2
 */
@RestController
@RequestMapping("wx/cart")
public class WxCart2Controller {
    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    CartMapper cartMapper;

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    GoodsProductMapper goodsProductMapper;
    @Autowired
    AddressMapper addressMapper;
    @Autowired
    CouponMapper couponMapper;
    @Autowired
    OrderGoodsMapper orderGoodsMapper;

    @Autowired
    AdMapper adMapper;
    @Autowired
    BrandMapper brandMapper;
    @Autowired
    GrouponMapper grouponMapper;
    @Autowired
    TopicMapper topicMapper;

    @RequestMapping("index")
    public BaseRespVo cartIndex(HttpSession httpSession) {

        Integer userId = (Integer) httpSession.getAttribute("userId");

        CartData cartData = new CartData();
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria1 = cartExample.createCriteria();
        criteria1.andUserIdEqualTo(userId);

        List<Cart> carts = cartMapper.selectByExample(cartExample);

        cartData.setCartList(carts);

        long cartcount = cartMapper.countByExample(cartExample);

        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andCheckedEqualTo(true);
        long checkedcount = cartMapper.countByExample(cartExample);


        CartExample amountExample = new CartExample();
        CartExample.Criteria amountExampleCriteria = amountExample.createCriteria();
        Iterator<Cart> iterator = carts.iterator();
        Double goodsAmount = 0.0;
        while(iterator.hasNext()){
            Cart cart = iterator.next();
            BigDecimal price = cart.getPrice();
            double value = price.doubleValue();
            Short number = cart.getNumber();
            goodsAmount+=value*number;

        }
       /* Double[] priceAll = cartMapper.selectPriceAll();
        Double goodsAmount = 0.0;
        for (Double price : priceAll
        ) {
            goodsAmount += price;
        }*/
        CartTotal cartTotal = new CartTotal();
        cartTotal.setGoodsAmount(goodsAmount);


        Double goodsCheckedAmount = 0.0;
        CartExample cartExample2 = new CartExample();
        CartExample.Criteria criteria2 = cartExample2.createCriteria();
        criteria2.andCheckedEqualTo(true);
        List<Cart> carts2 = cartMapper.selectByExample(cartExample2);

        Iterator<Cart> iterator2 = carts2.iterator();

        while(iterator2.hasNext()){
            Cart cart = iterator2.next();
            BigDecimal price = cart.getPrice();
            double value = price.doubleValue();
            Short number = cart.getNumber();
            goodsCheckedAmount+=value*number;

        }

        cartTotal.setCheckedGoodsAmount(goodsCheckedAmount);
        cartTotal.setCheckedGoodsCount((double) checkedcount);
        cartTotal.setGoodsCount((double) cartcount);

        cartData.setCartTotal(cartTotal);
        return BaseRespVo.ok(cartData);
    }

    @RequestMapping("add")
    public BaseRespVo add(@RequestBody FastAddData fastAddData,HttpSession httpSession){

        //获得用户id
        //int i =1;
        Integer roleId = (Integer) httpSession.getAttribute("userId");
        Integer goodsId = fastAddData.getGoodsId();
        Short number = fastAddData.getNumber();
        Integer productId = fastAddData.getProductId();
        GoodsProduct goodsProduct = goodsProductMapper.selectByPrimaryKey(productId);
        Goods goods = goodsMapper.selectByPrimaryKey(goodsId);
        Cart cart = new Cart();
        cart.setProductId(productId);
        cart.setGoodsSn(goods.getGoodsSn());
        cart.setPrice(goods.getRetailPrice());
        cart.setGoodsName(goods.getName());
        cart.setGoodsId(goods.getId());
        Date date = new Date();
        cart.setAddTime(date);
        cart.setPicUrl(goods.getPicUrl());
        cart.setUserId(roleId);
        cart.setNumber(number);
        if (cartMapper.selectByproductId(productId) != null) {
            Short number1 = cartMapper.selectByproductId(productId).getNumber();
            Integer id = cartMapper.selectByproductId(productId).getId();
            Integer i=number+number1;
            cartMapper.updateNumberById(id, i);
        } else {
            cartMapper.insertSelective(cart);
        }

        //int i = cartMapper.insertSelective(cart);
        long cartcount = cartMapper.countCartNumber(roleId);
        return BaseRespVo.listOk(cartcount);
     /*   Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            //在已经认证成功的情况下，可以获得用户信息
            // 获得的用户信息的来源 → 来源realm的doGetAuthenticationInfo方法的返回值的第一个参数
            Object primaryPrincipal = subject.getPrincipals().getPrimaryPrincipal();
        }*/
       // return null;
    }

    @RequestMapping("goodscount")
    public BaseRespVo goodscount() {
        CartExample cartExample = new CartExample();
        long cartcount = cartMapper.countByExample(cartExample);
        return BaseRespVo.ok(cartcount);
    }


    @RequestMapping("fastadd")
    public BaseRespVo fastadd(@RequestBody FastAddData fastAddData) {
        Goods goods = goodsMapper.selectByPrimaryKey(fastAddData.getGoodsId());
        Cart cart = new Cart();
        cart.setGoodsId(goods.getId());
        cart.setNumber(fastAddData.getNumber());
        cart.setProductId(fastAddData.getProductId());
        cart.setGoodsName(goods.getName());
        cart.setGoodsSn(goods.getGoodsSn());
        cart.setPrice(goods.getRetailPrice());
        Date date = new Date();
        cart.setAddTime(date);
        cart.setChecked(false);
        int i = cartMapper.insertSelective(cart);
        Integer cartId = cart.getId();
        return BaseRespVo.ok(cartId);
    }

    @RequestMapping("checkout")
    public BaseRespVo checkout(HttpSession httpSession) {
        CheckOutData checkOutData = new CheckOutData();
        // 查询actualPrice
        CartExample amountExample = new CartExample();
        CartExample.Criteria amountExampleCriteria = amountExample.createCriteria();
       // Double[] priceAll = cartMapper.selectPriceAll();

        Double goodsAmount = 0.0;
        Integer userId = (Integer) httpSession.getAttribute("userId");

        CartData cartData = new CartData();
        CartExample cartExample1 = new CartExample();
        CartExample.Criteria criteria3 = cartExample1.createCriteria();
        criteria3.andUserIdEqualTo(userId);

        List<Cart> carts2 = cartMapper.selectByExample(cartExample1);

        Iterator<Cart> iterator = carts2.iterator();

        while(iterator.hasNext()){
            Cart cart = iterator.next();
            BigDecimal price = cart.getPrice();
            double value = price.doubleValue();
            Short number = cart.getNumber();
            goodsAmount+=value*number;

        }

        checkOutData.setGoodsTotalPrice(goodsAmount);
        // 查询List<GoodsProduct>
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria1 = cartExample.createCriteria();
        criteria1.andCheckedEqualTo(true);
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        checkOutData.setCheckedGoodsList(carts);

        //查询 isdefault 为 ture 的LIST<Address>
        AddressExample addressExample = new AddressExample();
        AddressExample.Criteria criteria = addressExample.createCriteria();
        criteria.andIsDefaultEqualTo(true);
        List<Address> addresses = addressMapper.selectByExample(addressExample);
        checkOutData.setCheckedAddress(addresses);
        //设置AddressId
        Integer addressid = addresses.get(0).getId();
        checkOutData.setAddressId(addressid);
        //设置CartId
    /*    goodsProductMapper.selectByExample()
        Integer cartid = goodsProducts.get(0).getId();*/
        checkOutData.setCartId(0);

        List<Double> list = couponMapper.selectByprice();
        Double discount = list.get(0);
        checkOutData.setCouponPrice(discount);

        List<Integer> idlist = couponMapper.selectIdByPrice();
        Integer couponid = idlist.get(0);
        checkOutData.setCouponId(couponid);

       // Double freightprice = orderGoodsMapper.selectFreightPrice();
        Double freightprice =2.0;
        /*if (freightprice == null) {
            freightprice = 0.0;
        }*/
        checkOutData.setFreightPrice(freightprice);
        //Double grouponprice = orderGoodsMapper.selectGroupOnPrice();
        Double grouponprice=2.0;
        checkOutData.setGrouponPrice(grouponprice);
        //Integer rulesid = orderGoodsMapper.selectgrouponRulesId();
        Integer rulesid = 1;
        checkOutData.setGrouponRulesId(rulesid);

        Double ordertotalprice = goodsAmount - discount;
        if (ordertotalprice <= 0) {
            ordertotalprice = 0.0;
        }
        checkOutData.setActualPrice(ordertotalprice);
        checkOutData.setOrderTotalPrice(ordertotalprice);

        checkOutData.setUserCouponId(0);

        return BaseRespVo.ok(checkOutData);
    }


    @RequestMapping("checked")
    public BaseRespVo checked(@RequestBody ProductData productIds) {
        Integer[] productIds1 = productIds.getProductIds();
        Boolean ischecked = productIds.getIsChecked();
        if (productIds1.length == 1) {
            int id = productIds1[0];
            Boolean bo = cartMapper.selectChecked(id);
            int i = cartMapper.updatecheckedById(id, ischecked);
        } else {
            for (Integer id : productIds1
            ) {
                Boolean bo = cartMapper.selectChecked(id);
                int i = cartMapper.updatecheckedByIdGroup(id, ischecked);
            }
        }


        CartData cartData = new CartData();
        CartExample cartExample = new CartExample();


        List<Cart> carts = cartMapper.selectByExample(cartExample);
        cartData.setCartList(carts);


        long cartcount = cartMapper.countByExample(cartExample);
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andCheckedEqualTo(true);
        long checkedcount = cartMapper.countByExample(cartExample);


        CartExample amountExample = new CartExample();
        CartExample.Criteria amountExampleCriteria = amountExample.createCriteria();
        Double[] priceAll = cartMapper.selectPriceAll();
        Double goodsAmount = 0.0;
        for (Double price : priceAll
        ) {
            goodsAmount += price;
        }
        CartTotal cartTotal = new CartTotal();
        cartTotal.setGoodsAmount(goodsAmount);


        Double goodsCheckedAmount = 0.0;
        Double[] priceChecked = cartMapper.selectPriceChecked();
        for (Double price : priceChecked
        ) {
            goodsCheckedAmount += price;
        }

        cartTotal.setCheckedGoodsAmount(goodsCheckedAmount);
        cartTotal.setCheckedGoodsCount((double) checkedcount);
        cartTotal.setGoodsCount((double) cartcount);

        cartData.setCartTotal(cartTotal);
        return BaseRespVo.ok(cartData);
    }

    @RequestMapping("update")
    public BaseRespVo update(@RequestBody UpdateData updateData) {
        int i = cartMapper.updateNumberById(updateData.getId(), updateData.getNumber());
        return BaseRespVo.out();
    }

    @RequestMapping("delete")
    public BaseRespVo delete(@RequestBody DeleteData productIds) {
        Integer[] productIds1 = productIds.getProductIds();
        for (Integer id : productIds1
        ) {
            int i = cartMapper.deleteByPid(id);
        }


        CartData cartData = new CartData();
        CartExample cartExample = new CartExample();


        List<Cart> carts = cartMapper.selectByExample(cartExample);
        cartData.setCartList(carts);


        long cartcount = cartMapper.countByExample(cartExample);
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andCheckedEqualTo(true);
        long checkedcount = cartMapper.countByExample(cartExample);


        CartExample amountExample = new CartExample();
        CartExample.Criteria amountExampleCriteria = amountExample.createCriteria();
        Double[] priceAll = cartMapper.selectPriceAll();
        Double goodsAmount = 0.0;
        for (Double price : priceAll
        ) {
            goodsAmount += price;
        }
        CartTotal cartTotal = new CartTotal();
        cartTotal.setGoodsAmount(goodsAmount);


        Double goodsCheckedAmount = 0.0;
        Double[] priceChecked = cartMapper.selectPriceChecked();
        for (Double price : priceChecked
        ) {
            goodsCheckedAmount += price;
        }

        cartTotal.setCheckedGoodsAmount(goodsCheckedAmount);
        cartTotal.setCheckedGoodsCount((double) checkedcount);
        cartTotal.setGoodsCount((double) cartcount);

        cartData.setCartTotal(cartTotal);
        return BaseRespVo.ok(cartData);
    }
}
